package com.swf.seed.security.cert;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.KeyStore;
import java.security.PrivateKey;
import java.security.Signature;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.swf.seed.util.CmdUtils;

public class SecurityKeyStore {
	private static Logger logger = LoggerFactory.getLogger(SecurityKeyStore.class);
	public static final String KEYTOOL = "keytool";
	public static final String CMD = "cmd ";
	public static final String CD = "cd ";
	public static final String _C = "/c ";
	public static final String _GENKEY = " -genkey ";// 1.4jdk创建keystore
	public static final String _GENKEYPAIR = " -genkeypair ";// 1.4以上jdk创建keystore
	public static final String _ALIAS = " -alias ";// 产生别名
	public static final String _KEYSTORE = " -keystore ";// 指定密钥库名
	public static final String _KEYALG = " -keyalg ";// 指定密钥算法，默认DES
	public static final String _VALIDITY = " -validity ";// 证书有效期天数
	public static final String _KEYSIZE = " -keysize ";// 指定密钥长度
	public static final String _STOREPASS = " -storepass ";// 指定密钥库的密码
	public static final String _KEYPASS = " -keypass ";// 指定别名条目的密码(私钥的密码)
	public static final String _DNAME = " -dname ";// 指定证书拥有者信息
													// "CN=名字与姓氏,OU=组织单位名称,O=组织名称,L=城市或区域名称,ST=州或省份名称,C=单位的两字母国家代码"
	public static final String _LIST = " -list ";// 显示密钥库中的证书信息
	public static final String _V = " -v ";// 显示密钥库中的证书详细信息
	public static final String _EXPORT = " -export ";// 将别名指定的证书导出到文件 keytool
														// -export -alias
														// 需要导出的别名 -keystore
														// 指定keystore -file
														// 指定导出的证书位置及证书名称
														// -storepass 密码
	public static final String _FILE = " -file ";// 参数指定导出到文件的文件名
	public static final String _DELETE = " -delete ";// 删除密钥库中某条目 keytool
														// -delete -alias
														// 指定需删除的别名 -keystore
														// 指定keystore -storepass
														// 密码
	public static final String _PRINTCERT = " -printcert ";// 查看导出的证书信息 keytool
															// -printcert -file
															// hundsun.crt
	public static final String _KEYPASSWD = " -keypasswd ";// 修改密钥库中指定条目口令
															// keytool
															// -keypasswd -alias
															// 需修改的别名 -keypass
															// 旧密码 -new 新密码
															// -storepass
															// keystore密码
															// -keystore
	public static final String _IMPORT = " -import ";// 将已签名数字证书导入密钥库 keytool
														// -import -alias
														// 指定导入条目的别名 -keystore
														// 指定keystore -file
														// 需导入的证书

	/**
	 * 返回生成秘钥串命令
	 * 
	 * @param alias
	 * @param keyalg
	 * @param keystore
	 * @param dname
	 * @param storepass
	 * @param keypass
	 */
	public static String genkeypair(String alias, String keyalg, String keystore, String dname, String storepass, String keypass) {
		StringBuilder sb = new StringBuilder();
		sb.append(CMD).append(_C).append(KEYTOOL).append(_GENKEYPAIR).append(_ALIAS).append(alias).append(_KEYALG).append(keyalg).append(_KEYSTORE).append(keystore).append(_DNAME).append(dname)
				.append(_STOREPASS).append(storepass).append(_KEYPASS).append(keypass);
		return sb.toString();
	}

	/**
	 * 查看密钥库里证书
	 * 
	 * @param keystore
	 */
	public static String list(String keystore, String storepass) {
		StringBuilder sb = new StringBuilder();
		sb.append(CMD).append(_C).append(KEYTOOL).append(_LIST).append(_V).append(_KEYSTORE).append(keystore).append(_STOREPASS).append(storepass);

		return sb.toString();
	}

	/**
	 * 导出证书文件
	 * 
	 * @param alias
	 * @param file
	 * @param keystore
	 * @param storepass
	 */
	public static String export(String alias, String file, String keystore, String storepass) {
		StringBuilder sb = new StringBuilder();
		sb.append(CMD).append(_C).append(KEYTOOL).append(_EXPORT).append(_ALIAS).append(alias).append(_FILE).append(file).append(_KEYSTORE).append(keystore).append(_STOREPASS).append(storepass);

		return sb.toString();
	}

	public static PrivateKey getPrivateKey(String alias, String keystore, String storepass) {
		PrivateKey key = null;
		char[] password = storepass.toCharArray();
		InputStream is = null;
		try {
			is = new FileInputStream(new File(keystore));
			KeyStore ks = KeyStore.getInstance("JKS");
			ks.load(is, password);
			key = (PrivateKey) ks.getKey(alias, password);
		} catch (Exception e) {
			logger.error("获取私钥失败", e);
		} finally {
			try {
				is.close();
			} catch (IOException ingoreExp) {
			}
		}
		return key;
	}
	
	public  String signature(Map<String, String> config, PrivateKey pk, String text){
		String signed = "";
		try {
			Signature sign = Signature.getInstance("MD5withRSA");
			sign.initSign(pk);
			if(!"".equals(text)){
				System.out.println(byteArrayToHexString(text.getBytes("GBK")));
				sign.update(text.getBytes("GBK"));
				BASE64Encoder encoder = new BASE64Encoder();
				signed = encoder.encode(sign.sign());
			}
		} catch (Exception e) {
			System.err.println("签名失败" + e);
		}
		return signed;
	}

	public static void main(String[] args) {
		String alias = "hundsun";
		String keyalg = "RSA";
		String keystore = "d:/hundsun.keystore";
		String dname = "CN=localhost,OU=hundsun,O=ecg,L=hangzhou,ST=zhejiang,C=86";
		String storepass = "123456";
		String keypass = "123456";
		String crtFile = "d:/hundsun.cer";
		new File(keystore).delete();
		new File(crtFile).delete();
		
		String result = CmdUtils.exec(genkeypair(alias, keyalg, keystore, dname, storepass, keypass));
		System.out.println(result);
		result = CmdUtils.exec(list(keystore, storepass));
		System.out.println(result);
		result = CmdUtils.exec(export(alias, crtFile, keystore, storepass));
		System.out.println(result);
		PrivateKey key = getPrivateKey(alias, keystore, storepass);
		System.out.println(key);
		
	}
}
